import Http from './../http/chatApiHttp'
export default class RonrIM{
  getTokenAndKey(params){
    return new Promise((resolve,reject)=> {
      Http.request({
        data: params,
        method: 'POST',
        url: '/im/getToken'
      }).then((res) => {
        resolve(res)
      })
    })
  }
  setConnectionStatusListener(){
    return new Promise((resolve,reject)=> {
      RongIMClient.setConnectionStatusListener({
        onChanged: function (status) {
          switch (status) {
            case RongIMLib.ConnectionStatus.CONNECTED:
              resolve();
              console.log('链接成功');
              break;
            case RongIMLib.ConnectionStatus.CONNECTING:
              console.log('正在链接');
              break;
            case RongIMLib.ConnectionStatus.DISCONNECTED:
              console.log('断开连接');
              break;
            case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
              console.log('其他设备登录');
              break;
            case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
              console.log('域名不正确');
              break;
            case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
              console.log('网络不可用');
              break;
          }
        }
      });
    })
  }
  RongIMClientConnect(token){
    return new Promise((resolve,reject)=> {
      RongIMClient.connect(token, {
        onSuccess: function (userId) {
          resolve()
          //console.log("Connect successfully." + userId);
        },
        onTokenIncorrect: function () {
          reject();
          console.log('token无效');
        },
        onError: function (errorCode) {
          reject();
         console.log(errorCode)
        }
      })
    })
  }
  //获取会话列表
  getConversationList(){
    return new Promise((resolve,reject)=>{
      RongIMClient.getInstance().getConversationList({
        onSuccess: function(list) {
          resolve(list);
        },
        onError: function(error) {
          reject(error)
          // do something...
        }
      },null);
    })

  }
  //获取历史消息
  getHistoryMessages(targetId,count,timestrap=null){

   return new Promise((resolve,reject)=>{
     let conversationType = RongIMLib.ConversationType.PRIVATE;
     RongIMLib.RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, timestrap, count, {
       onSuccess: function(list, hasMsg) {
         list.sort(function(a,b){
           return a.sentTime > b.sentTime;
         });

         let obj ={
           list:list,
           hasMsg:hasMsg
         };
         resolve(obj)
         // list => Message 数组。
         // hasMsg => 是否还有历史消息可以获取。
       },
       onError: function(error) {
         reject(error);
         console.log("GetHistoryMessages,errorcode:" + error);
       }
     });
   })
  }
  //获取总共未读消息数量
  getTotalUnreadCount(){
    return new Promise((resolve,reject)=>{
      RongIMClient.getInstance().getTotalUnreadCount({
        onSuccess:function(count){
          resolve(count)
          // count => 所有会话总未读数。
        },
        onError:function(error){
          reject(error)
          // error => 获取总未读数错误码。
        }
      });
    })

  }
  //清除未读消息
  clearUnreadCount(targetId){
   return new Promise((resolve,reject)=>{
     let conversationType = RongIMLib.ConversationType.PRIVATE;
     RongIMClient.getInstance().clearUnreadCount(conversationType,targetId,{
       onSuccess:function(){
         resolve()
         // 清除未读消息成功。
       },
       onError:function(error){
         reject(error)
         // error => 清除未读消息数错误码。
       }
     });
   })
  }

  //发送文本消息
  sendTextMessage(targetId,content,extra=null){
    let msg = new RongIMLib.TextMessage({content:content,extra:extra});
    return new Promise((resolve,reject)=>{
      this.sendMessage(targetId,msg).then((message)=>{
        resolve(message)
      });
    });
  }
  sendMessage(targetId,msg){
    let conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可
    return new Promise((resolve,reject)=>{
      RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
            onSuccess: function (message) {
              //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
              resolve(message)
            },
            onError: function (errorCode,message) {
              reject(message);
              console.log('发送失败:' + errorCode);
            }
          }
      );
    })
  }

}
